<template>
  <div class="scoll-wrap">
    <div class="scroll-content" ref="scrollContent">
      <slot></slot>
    </div>
    <div class="control">
      <div class="slide-tip">
        <span class="slide-index">{{ currentPage }}</span>
        /
        <span class="slide-max">{{ totalPages }}</span>
      </div>
      <div class="left" @click="prePage"></div>
      <div class="right" @click="nextPage"></div>
    </div>
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from 'vue';
const {proxy} = getCurrentInstance(); // 获取上下文对象
let translateX = 0; // 滚动的距离
const unit = 675; // (115 + 10 + 10)*5 = 675 每次移动的距离
const totalPages = ref(0); // 总页数
const currentPage = ref(1); // 当前页数

// 向前翻页
const prePage = () => {
  translateX = translateX - unit;
  if (translateX <= 0) {
    translateX = 0;
    currentPage.value = 1;
  } else {
    currentPage.value -= 1;
  }
  proxy.$refs.scrollContent.style.transform = 'translateX(-' + translateX + 'px)';
};

// 向后翻页
const nextPage = () => {
  translateX = translateX + unit;
  let maxwidth = proxy.$refs.scrollContent.clientWidth;
  if (translateX >= maxwidth) {
    translateX = Math.max(maxwidth - unit, translateX - unit);
  } else {
    currentPage.value += 1;
  }
  proxy.$refs.scrollContent.style.transform = 'translateX(-' + translateX + 'px)';
};

onMounted(() => {
  totalPages.value = Math.ceil(proxy.$refs.scrollContent.scrollWidth / unit);
});
</script>

<style scoped lang="less">
.scoll-wrap {
  overflow: hidden;
}

.scroll-content {
  white-space: nowrap;
  display: inline-block;
  transition: transform 0.5s ease;
}

.control {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.left {
  width: 18px;
  height: 18px;
  background-image: url('/imgs/slide_swithc_2.png');
  cursor: pointer;
}

.right {
  margin-left: 4px;;
  width: 18px;
  height: 18px;
  background-image: url('/imgs/slide_swithc_2.png');
  background-position-x: -18px;
  cursor: pointer;
}


.slide-tip {
  font: 12px Helvetica,Arial,sans-serif;
  color: #666;
  margin-top: 2px;
  margin-right: 10px;
}
</style>
